# -*- coding: utf-8 -*-
"""
Author: chen xi
Date: 2025/5/22 下午3:48
File: screen_capture_utility.py
"""

import uiautomator2 as u2

# 连接到设备
d = u2.connect()


def capture_element_screenshot(_driver, _element, screenshot_path):
	"""
	对指定元素进行截图

	参数:
		_driver: 已连接的 uiautomator2 设备对象
		_element: uiautomator2 的 UiObject 对象，代表要截图的元素
		screenshot_path: 截图保存路径
	"""
	# 获取整个屏幕的截图
	screen = _driver.screenshot()
	
	# 获取元素的位置和大小
	bounds = _element.info['bounds']
	left, top, right, bottom = bounds['left'], bounds['top'], bounds['right'], bounds['bottom']
	
	# 裁剪出元素的截图
	cropped_img = screen.crop((left, top, right, bottom))
	
	# 保存裁剪后的图片
	cropped_img.save(screenshot_path)
	print(f"Element screenshot saved to {screenshot_path}")


# 示例用法
if __name__ == "__main__":
	import time

	# 查找要截图的元素，例如一个名为 "Screen timeout" 的列表项
	element = d(resourceId="com.zwcode.p6slite:id/easy_player_monitor")[1]
	
	if element.exists:
		capture_element_screenshot(d, element, f"../../temp/element_screenshot_{int(time.time())}.png")
	else:
		print("Element not found.")